//
//  UserAccount.swift
//  weibo项目
//
//  Created by mac on 16/1/13.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {

    var access_token:String?
    var expires_in:NSTimeInterval = 0 {
//        给过期的时间复赋值
        didSet{
              expires_date = NSDate(timeIntervalSinceNow:expires_in)
        }
  
    
    
    }
//    当前授权用户的uid
    var uid:String?
//    获取用户的名字
    var name:String?
//    获取用户的图像
    var avatar_larger:String?
//    过期的时间
    var expires_date:NSDate?
    
//    在初始化的时候直接把字典传出来
    init(dict:[String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
//     重写对象的描述方法
   override   var description:String{
    
    let keys = ["access_token","expires_in","uid","name","avatar_larger"]
    let dict = self.dictionaryWithValuesForKeys(keys)
    
    return dict.description
    }
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
//        基本数据类型可以用 可以直接解归档到具体的数据类型
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        name = aDecoder.decodeObjectForKey("name")as? String
        avatar_larger = aDecoder.decodeObjectForKey("avatar_larger") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
    
//    归档
    func encodeWithCoder(aCoder: NSCoder) {
     aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(avatar_larger, forKey: "avatar_larger")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
    }
    
//    把数据保存到沙河中
     func saveData(){
    let  path = ( NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString) .stringByAppendingPathComponent("account.plist")
        print(path)
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
//    把数据读取出来 用类方法
    class func loaUserAccount() ->UserAccount? {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
//        时间的比较,当时间没有 超过过期的时间的时候 可以返回account
       if let  account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount{
      if  account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
        
         return account
        }
       
        
        }
        return nil
  
        
    }
    
    
    }
    

